package org.yankun.exam4j.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.yankun.exam4j.entity.Passport;
import org.yankun.exam4j.entity.User;
import org.yankun.exam4j.security.passport.service.PassportService;
import org.yankun.exam4j.security.user.service.UserService;
import org.yankun.exam4j.session.SessionManager;
import org.yankun.exam4j.session.UserSessionData;



@Controller("LoginController")
@RequestMapping("/login")
public class LoginController {
	
	@Resource
	private PassportService passportService;
	
	@Resource
	private UserService userService;
	
	@Resource
	private SessionManager sessionManager;
	
	@RequestMapping()
	public ModelAndView toIndex(HttpServletResponse response,HttpServletRequest request
			){
		return new ModelAndView("/login/login",null);
	}
	
	@RequestMapping("doLogin")
	public String doLogin(HttpServletResponse response,HttpServletRequest request,Passport passport){
		HttpSession session=request.getSession();
		
//		String code = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		
		Passport pass = passportService.verifyUser(passport);
		
		if(pass != null){
			User user = userService.getUserByPassport(pass);
			
			UserSessionData data = new UserSessionData(session.getId(), user.getUid(), pass.getUsername(), false);
			
			sessionManager.login(session, data);
			
			return "redirect:/dashboard/index.do";
		}
		
		return "redirect:/login.do?state=error";
	}
	
	@RequestMapping("doLogout")
	public String doLogout(HttpServletResponse response,HttpServletRequest request){
		HttpSession session = request.getSession(false);
		if (null != session) {
		    session.invalidate();	//set session invalidate;
		}
		return "redirect:/login.do";
	}
}